home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / cmd.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  16.0 KB  |  455 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. '''A generic class to build line-oriented command interpreters.
  5.  
  6. Interpreters constructed with this class obey the following conventions:
  7.  
  8. 1. End of file on input is processed as the command \'EOF\'.
  9. 2. A command is parsed out of each line by collecting the prefix composed
  10.    of characters in the identchars member.
  11. 3. A command `foo\' is dispatched to a method \'do_foo()\'; the do_ method
  12.    is passed a single argument consisting of the remainder of the line.
  13. 4. Typing an empty line repeats the last command.  (Actually, it calls the
  14.    method `emptyline\', which may be overridden in a subclass.)
  15. 5. There is a predefined `help\' method.  Given an argument `topic\', it
  16.    calls the command `help_topic\'.  With no arguments, it lists all topics
  17.    with defined help_ functions, broken into up to three topics; documented
  18.    commands, miscellaneous help topics, and undocumented commands.
  19. 6. The command \'?\' is a synonym for `help\'.  The command \'!\' is a synonym
  20.    for `shell\', if a do_shell method exists.
  21. 7. If completion is enabled, completing commands will be done automatically,
  22.    and completing of commands args is done by calling complete_foo() with
  23.    arguments text, line, begidx, endidx.  text is string we are matching
  24.    against, all returned matches must begin with it.  line is the current
  25.    input line (lstripped), begidx and endidx are the beginning and end
  26.    indexes of the text being matched, which could be used to provide
  27.    different completion depending upon which position the argument is in.
  28.  
  29. The `default\' method may be overridden to intercept commands for which there
  30. is no do_ method.
  31.  
  32. The `completedefault\' method may be overridden to intercept completions for
  33. commands that have no complete_ method.
  34.  
  35. The data member `self.ruler\' sets the character used to draw separator lines
  36. in the help messages.  If empty, no ruler line is drawn.  It defaults to "=".
  37.  
  38. If the value of `self.intro\' is nonempty when the cmdloop method is called,
  39. it is printed out on interpreter startup.  This value may be overridden
  40. via an optional argument to the cmdloop() method.
  41.  
  42. The data members `self.doc_header\', `self.misc_header\', and
  43. `self.undoc_header\' set the headers used for the help function\'s
  44. listings of documented functions, miscellaneous topics, and undocumented
  45. functions respectively.
  46.  
  47. These interpreters use raw_input; thus, if the readline module is loaded,
  48. they automatically support Emacs-like command history and editing features.
  49. '''
  50. import string
  51. __all__ = [
  52.     'Cmd']
  53. PROMPT = '(Cmd) '
  54. IDENTCHARS = string.ascii_letters + string.digits + '_'
  55.  
  56. class Cmd:
  57.     """A simple framework for writing line-oriented command interpreters.
  58.  
  59.     These are often useful for test harnesses, administrative tools, and
  60.     prototypes that will later be wrapped in a more sophisticated interface.
  61.  
  62.     A Cmd instance or subclass instance is a line-oriented interpreter
  63.     framework.  There is no good reason to instantiate Cmd itself; rather,
  64.     it's useful as a superclass of an interpreter class you define yourself
  65.     in order to inherit Cmd's methods and encapsulate action methods.
  66.  
  67.     """
  68.     prompt = PROMPT
  69.     identchars = IDENTCHARS
  70.     ruler = '='
  71.     lastcmd = ''
  72.     intro = None
  73.     doc_leader = ''
  74.     doc_header = 'Documented commands (type help <topic>):'
  75.     misc_header = 'Miscellaneous help topics:'
  76.     undoc_header = 'Undocumented commands:'
  77.     nohelp = '*** No help on %s'
  78.     use_rawinput = 1
  79.     
  80.     def __init__(self, completekey = 'tab', stdin = None, stdout = None):
  81.         """Instantiate a line-oriented interpreter framework.
  82.  
  83.         The optional argument 'completekey' is the readline name of a
  84.         completion key; it defaults to the Tab key. If completekey is
  85.         not None and the readline module is available, command completion
  86.         is done automatically. The optional arguments stdin and stdout
  87.         specify alternate input and output file objects; if not specified,
  88.         sys.stdin and sys.stdout are used.
  89.  
  90.         """
  91.         import sys
  92.         if stdin is not None:
  93.             self.stdin = stdin
  94.         else:
  95.             self.stdin = sys.stdin
  96.         if stdout is not None:
  97.             self.stdout = stdout
  98.         else:
  99.             self.stdout = sys.stdout
  100.         self.cmdqueue = []
  101.         self.completekey = completekey
  102.  
  103.     
  104.     def cmdloop(self, intro = None):
  105.         '''Repeatedly issue a prompt, accept input, parse an initial prefix
  106.         off the received input, and dispatch to action methods, passing them
  107.         the remainder of the line as argument.
  108.  
  109.         '''
  110.         self.preloop()
  111.         if intro is not None:
  112.             self.intro = intro
  113.         
  114.         if self.intro:
  115.             self.stdout.write(str(self.intro) + '\n')
  116.         
  117.         stop = None
  118.         while not stop:
  119.             if self.cmdqueue:
  120.                 line = self.cmdqueue.pop(0)
  121.             elif self.use_rawinput:
  122.                 
  123.                 try:
  124.                     line = raw_input(self.prompt)
  125.                 except EOFError:
  126.                     line = 'EOF'
  127.                 except:
  128.                     None<EXCEPTION MATCH>EOFError
  129.                 
  130.  
  131.             None<EXCEPTION MATCH>EOFError
  132.             self.stdout.write(self.prompt)
  133.             self.stdout.flush()
  134.             line = self.stdin.readline()
  135.             if not len(line):
  136.                 line = 'EOF'
  137.             else:
  138.                 line = line[:-1]
  139.             line = self.precmd(line)
  140.             stop = self.onecmd(line)
  141.             stop = self.postcmd(stop, line)
  142.         self.postloop()
  143.  
  144.     
  145.     def precmd(self, line):
  146.         '''Hook method executed just before the command line is
  147.         interpreted, but after the input prompt is generated and issued.
  148.  
  149.         '''
  150.         return line
  151.  
  152.     
  153.     def postcmd(self, stop, line):
  154.         '''Hook method executed just after a command dispatch is finished.'''
  155.         return stop
  156.  
  157.     
  158.     def preloop(self):
  159.         '''Hook method executed once when the cmdloop() method is called.'''
  160.         if self.completekey:
  161.             
  162.             try:
  163.                 import readline
  164.                 self.old_completer = readline.get_completer()
  165.                 readline.set_completer(self.complete)
  166.                 readline.parse_and_bind(self.completekey + ': complete')
  167.             except ImportError:
  168.                 pass
  169.             except:
  170.                 None<EXCEPTION MATCH>ImportError
  171.             
  172.  
  173.         None<EXCEPTION MATCH>ImportError
  174.  
  175.     
  176.     def postloop(self):
  177.         '''Hook method executed once when the cmdloop() method is about to
  178.         return.
  179.  
  180.         '''
  181.         if self.completekey:
  182.             
  183.             try:
  184.                 import readline
  185.                 readline.set_completer(self.old_completer)
  186.             except ImportError:
  187.                 pass
  188.             except:
  189.                 None<EXCEPTION MATCH>ImportError
  190.             
  191.  
  192.         None<EXCEPTION MATCH>ImportError
  193.  
  194.     
  195.     def parseline(self, line):
  196.         line = line.strip()
  197.         if not line:
  198.             return (None, None, line)
  199.         elif line[0] == '?':
  200.             line = 'help ' + line[1:]
  201.         elif line[0] == '!':
  202.             if hasattr(self, 'do_shell'):
  203.                 line = 'shell ' + line[1:]
  204.             else:
  205.                 return (None, None, line)
  206.         
  207.         (i, n) = (0, len(line))
  208.         while i < n and line[i] in self.identchars:
  209.             i = i + 1
  210.         (cmd, arg) = (line[:i], line[i:].strip())
  211.         return (cmd, arg, line)
  212.  
  213.     
  214.     def onecmd(self, line):
  215.         '''Interpret the argument as though it had been typed in response
  216.         to the prompt.
  217.  
  218.         This may be overridden, but should not normally need to be;
  219.         see the precmd() and postcmd() methods for useful execution hooks.
  220.         The return value is a flag indicating whether interpretation of
  221.         commands by the interpreter should stop.
  222.  
  223.         '''
  224.         (cmd, arg, line) = self.parseline(line)
  225.         if not line:
  226.             return self.emptyline()
  227.         
  228.         if cmd is None:
  229.             return self.default(line)
  230.         
  231.         self.lastcmd = line
  232.         if cmd == '':
  233.             return self.default(line)
  234.         else:
  235.             
  236.             try:
  237.                 func = getattr(self, 'do_' + cmd)
  238.             except AttributeError:
  239.                 return self.default(line)
  240.  
  241.             return func(arg)
  242.  
  243.     
  244.     def emptyline(self):
  245.         '''Called when an empty line is entered in response to the prompt.
  246.  
  247.         If this method is not overridden, it repeats the last nonempty
  248.         command entered.
  249.  
  250.         '''
  251.         if self.lastcmd:
  252.             return self.onecmd(self.lastcmd)
  253.         
  254.  
  255.     
  256.     def default(self, line):
  257.         '''Called on an input line when the command prefix is not recognized.
  258.  
  259.         If this method is not overridden, it prints an error message and
  260.         returns.
  261.  
  262.         '''
  263.         self.stdout.write('*** Unknown syntax: %s\n' % line)
  264.  
  265.     
  266.     def completedefault(self, *ignored):
  267.         '''Method called to complete an input line when no command-specific
  268.         complete_*() method is available.
  269.  
  270.         By default, it returns an empty list.
  271.  
  272.         '''
  273.         return []
  274.  
  275.     
  276.     def completenames(self, text, *ignored):
  277.         dotext = 'do_' + text
  278.         return []
  279.  
  280.     
  281.     def complete(self, text, state):
  282.         """Return the next possible completion for 'text'.
  283.  
  284.         If a command has not been entered, then complete against command list.
  285.         Otherwise try to call complete_<command> to get list of completions.
  286.         """
  287.         if state == 0:
  288.             import readline
  289.             origline = readline.get_line_buffer()
  290.             line = origline.lstrip()
  291.             stripped = len(origline) - len(line)
  292.             begidx = readline.get_begidx() - stripped
  293.             endidx = readline.get_endidx() - stripped
  294.             if begidx > 0:
  295.                 (cmd, args, foo) = self.parseline(line)
  296.             None if cmd == '' else None<EXCEPTION MATCH>AttributeError
  297.             compfunc = self.completenames
  298.             self.completion_matches = compfunc(text, line, begidx, endidx)
  299.         
  300.         
  301.         try:
  302.             return self.completion_matches[state]
  303.         except IndexError:
  304.             return None
  305.  
  306.  
  307.     
  308.     def get_names(self):
  309.         names = []
  310.         classes = [
  311.             self.__class__]
  312.         while classes:
  313.             aclass = classes.pop(0)
  314.             if aclass.__bases__:
  315.                 classes = classes + list(aclass.__bases__)
  316.             
  317.             names = names + dir(aclass)
  318.         return names
  319.  
  320.     
  321.     def complete_help(self, *args):
  322.         return self.completenames(*args)
  323.  
  324.     
  325.     def do_help(self, arg):
  326.         if arg:
  327.             
  328.             try:
  329.                 func = getattr(self, 'help_' + arg)
  330.             except AttributeError:
  331.                 
  332.                 try:
  333.                     doc = getattr(self, 'do_' + arg).__doc__
  334.                     if doc:
  335.                         self.stdout.write('%s\n' % str(doc))
  336.                         return None
  337.                 except AttributeError:
  338.                     pass
  339.  
  340.                 self.stdout.write('%s\n' % str(self.nohelp % (arg,)))
  341.                 return None
  342.  
  343.             func()
  344.         else:
  345.             names = self.get_names()
  346.             cmds_doc = []
  347.             cmds_undoc = []
  348.             help = { }
  349.             for name in names:
  350.                 if name[:5] == 'help_':
  351.                     help[name[5:]] = 1
  352.                     continue
  353.             
  354.             names.sort()
  355.             prevname = ''
  356.             for name in names:
  357.                 if name[:3] == 'do_':
  358.                     if name == prevname:
  359.                         continue
  360.                     
  361.                     prevname = name
  362.                     cmd = name[3:]
  363.                     if cmd in help:
  364.                         cmds_doc.append(cmd)
  365.                         del help[cmd]
  366.                     elif getattr(self, name).__doc__:
  367.                         cmds_doc.append(cmd)
  368.                     else:
  369.                         cmds_undoc.append(cmd)
  370.                 cmd in help
  371.             
  372.             self.stdout.write('%s\n' % str(self.doc_leader))
  373.             self.print_topics(self.doc_header, cmds_doc, 15, 80)
  374.             self.print_topics(self.misc_header, help.keys(), 15, 80)
  375.             self.print_topics(self.undoc_header, cmds_undoc, 15, 80)
  376.  
  377.     
  378.     def print_topics(self, header, cmds, cmdlen, maxcol):
  379.         if cmds:
  380.             self.stdout.write('%s\n' % str(header))
  381.             if self.ruler:
  382.                 self.stdout.write('%s\n' % str(self.ruler * len(header)))
  383.             
  384.             self.columnize(cmds, maxcol - 1)
  385.             self.stdout.write('\n')
  386.         
  387.  
  388.     
  389.     def columnize(self, list, displaywidth = 80):
  390.         '''Display a list of strings as a compact set of columns.
  391.  
  392.         Each column is only as wide as necessary.
  393.         Columns are separated by two spaces (one was not legible enough).
  394.         '''
  395.         if not list:
  396.             self.stdout.write('<empty>\n')
  397.             return None
  398.         
  399.         nonstrings = []
  400.         if nonstrings:
  401.             raise TypeError, 'list[i] not a string for i in %s' % ', '.join(map(str, nonstrings))
  402.         
  403.         size = len(list)
  404.         if size == 1:
  405.             self.stdout.write('%s\n' % str(list[0]))
  406.             return None
  407.         
  408.         for nrows in range(1, len(list)):
  409.             ncols = (size + nrows - 1) // nrows
  410.             colwidths = []
  411.             totwidth = -2
  412.             for col in range(ncols):
  413.                 colwidth = 0
  414.                 for row in range(nrows):
  415.                     i = row + nrows * col
  416.                     if i >= size:
  417.                         break
  418.                     
  419.                     x = list[i]
  420.                     colwidth = max(colwidth, len(x))
  421.                 
  422.                 colwidths.append(colwidth)
  423.                 totwidth += colwidth + 2
  424.                 if totwidth > displaywidth:
  425.                     break
  426.                     continue
  427.             
  428.             if totwidth <= displaywidth:
  429.                 break
  430.                 continue
  431.         else:
  432.             nrows = len(list)
  433.             ncols = 1
  434.             colwidths = [
  435.                 0]
  436.         for row in range(nrows):
  437.             texts = []
  438.             for col in range(ncols):
  439.                 i = row + nrows * col
  440.                 if i >= size:
  441.                     x = ''
  442.                 else:
  443.                     x = list[i]
  444.                 texts.append(x)
  445.             
  446.             while texts and not texts[-1]:
  447.                 del texts[-1]
  448.             for col in range(len(texts)):
  449.                 texts[col] = texts[col].ljust(colwidths[col])
  450.             
  451.             self.stdout.write('%s\n' % str('  '.join(texts)))
  452.         
  453.  
  454.  
  455.